#include 	"queue.h"
#include 	"includes.h"



QUEUE_Frame Queue_Frame_Usart2;	
QUEUE_Frame Queue_Frame_Usart3;	


UINT8 USART2_Queue_Buf[Max_Queue_Size_USART2];
UINT8 DMA_UART2_TX_Buf[DMA_TX2_LEN];
UINT8 DMA_UART2_RX_Buf[DMA_RX2_LEN];


UINT8 USART3_Queue_Buf[Max_Queue_Size_USART3];
UINT8 DMA_UART3_TX_Buf[DMA_TX3_LEN];
UINT8 DMA_UART3_RX_Buf[DMA_RX3_LEN];


INT32 CreateQueue_Frame(QUEUE_Frame *q, INT32 qsize, UINT8 *qBUF, UINT8 *txBUF, UINT8 *rxBUF)
{

//    q->qu=(int *)malloc(sizeof(int)*maxsize);
//    if(NULL==q->qu)
//    {
//        printf("Memory allocation failure");
//        return -1;        
//    }
	q->qu = qBUF;
	q->maxsize = qsize;
	q->DMA_UARTn_TX_Buf = txBUF;
	q->DMA_UARTn_RX_Buf = rxBUF;	
	
	INIT_Queue_Frame(q);	
    return 0;
}
INT32 INIT_Queue_Frame(QUEUE_Frame *q)
{
	q->head = 0;
    q->tail = 0;
    q->qlength = 0;

	
	q->FrameCnt = 0;
	q->FrameIn = 0;
	q->FrameOut = 0;
	return 0;
}

INT32 isEmpty (QUEUE_Frame *q)
{
   return  q->qlength == 0 ? 0 : -1;
}


INT32 isFull (QUEUE_Frame *q)
{
    return q->qlength == q->maxsize ? 0 : -1;
}

//
INT32 Enqueue (QUEUE_Frame *q , UINT8 *buf,INT32 size)
{
INT32	tmp1,tmp2;
    if (isFull(q) == 0) 
	{
        return -1;
    }
	else
	{
		if ((q->qlength + size) > q->maxsize)
		{
			return -1;
		}
		if (q->FrameCnt > Max_Frame_Num)
		{
			return -1;
		}	
		
		//---边界处理
		if ((q->tail + size) <= q->maxsize) 
		{
			memcpy(&q->qu[q->tail],buf,size);	
			
		}	
		else
		{
			tmp1 =	q->maxsize  - q->tail;						
			tmp2 = q->tail + size - q->maxsize;
			
			memcpy(&q->qu[q->tail],&buf[0],tmp1);
			memcpy(&q->qu[0],&buf[tmp1],tmp2);
		}	
		
		q->FrameLen[q->FrameIn] = size;
		q->FrameCnt++;
		q->FrameIn = (q->FrameIn+1)%Max_Frame_Num;
		
        q->tail = (q->tail + size)%q->maxsize;
        q->qlength = q->qlength + size;
    }
	return 0;
}

INT32 Dequeue (QUEUE_Frame *q, UINT8 *buf,INT32 size)
{
 INT32	tFrameLen; 
 INT32  tmp1,tmp2;	
    if (isEmpty(q) == 0) 
	{
        return -1;
    }
	else
	{	
		if ((q->FrameCnt > Max_Frame_Num) || (q->FrameCnt == 0))
		{
			return -1;
		}	
		if (q->FrameLen[q->FrameOut] > size)	
		{
			tFrameLen = q->FrameLen[q->FrameOut]; 
			q->FrameCnt--;
			q->FrameOut = (q->FrameOut+1)%Max_Frame_Num;
					
			q->head = (q->head +tFrameLen)%q->maxsize;  
			q->qlength -= tFrameLen;
			return -1;
		}	
		else
		{
			tFrameLen = q->FrameLen[q->FrameOut]; 
			
				
			
			if ((q->head + tFrameLen) <= q->maxsize) 
			{
				memcpy(buf,&q->qu[q->head],tFrameLen);			
			}	
			else
			{
				tmp1 =	q->maxsize  - q->head ;						
				tmp2 = q->head + tFrameLen - q->maxsize;
				
				memcpy(&buf[0],&q->qu[q->head],tmp1);
				memcpy(&buf[tmp1],&q->qu[0],tmp2);
			}
			q->FrameCnt--;
			q->FrameOut = (q->FrameOut+1)%Max_Frame_Num;
					
			q->head = (q->head +tFrameLen)%q->maxsize;  
			q->qlength -= tFrameLen;
		}	
    }
	return tFrameLen;
}




